package arrays;
import java.util.*;
/**
 * Created with IntelliJ IDEA.
 * Description: 704.二分查找
 * User: Li_yizYa
 * Date: 2025—03—20
 * Time: 19:23
 */
public class Solution1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("请输入要查找数组的长度: ");
        int n = scan.nextInt();
        int[] nums = new int[n];
        System.out.print("请输入有序数组的值: ");
        for (int i = 0; i < nums.length; i++) {
            nums[i] = scan.nextInt();
        }
        System.out.print("请输入要查找的数字: ");
        int target = scan.nextInt();
        int ret = search(nums, target);
        System.out.println("要查找数字的下标为: " + ret);
    }
    private static int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
